package com.yanftch.stopcoding.common.network;

import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class HttpUtils {
    private static final ExecutorService executorService = new ThreadPoolExecutor(1, 4, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    public static final int READ_TIMEOUT_IN_MILLIONS = 10000;
    public static final int CONNECT_TIMEOUT_IN_MILLIONS = 6000;

    private static Headers headers = Headers.Companion.of(new HashMap<String, String>());

    public static Headers getHeaders() {
        return headers;
    }

    public static void setHeaders(Map<String, String> mapHeaders) {
        headers = Headers.Companion.of(mapHeaders);
    }

    public static void get(String url, CallBack callBack) {
        http(HttpMethod.GET, url, callBack);
    }

    public static void post(String url, CallBack callBack) {
        http(HttpMethod.POST, url, callBack);
    }

    private static void http(HttpMethod httpMethod, String url, CallBack callBack) {
        OkHttpClient.Builder builder1 = new OkHttpClient.Builder();
        OkHttpClient client = null;
        try {
            // 创建请求
//                hMap.put("Cookie", "SUB=_2AkMQUXTgf8NxqwFRmf4VzGnkaI1zzQHEieKmDYU7JRMxHRl-yT9kqkhStRB6O9FaD1cEwKM32NnxNptG8A2i-2KTP4T9" + ";SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WWhnThkBXkehJIPX9Op.1Lh");
            Request.Builder builder = new Request.Builder();
            TrustManager[] trustAllCerts = buildTrustManagers();
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder1.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder1.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            client = builder1.build();

            Request request = builder.url(url).get().headers(headers).build();

            OkHttpClient finalClient = client;
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    if (callBack != null) {
                        callBack.onError(e);
                    }
                    finalClient.dispatcher().executorService().shutdown();
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    if (callBack != null) {
                        if (200 == response.code() && response.body() != null) {
                            callBack.onSuccess(response.body().string());
                        } else {
                            callBack.onError(new Exception("接口请求异常~"));
                        }
                    }
                    finalClient.dispatcher().executorService().shutdown();
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            client.dispatcher().executorService().shutdown();
        }
    }


    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[0];
                    }
                }
        };
    }
}
